#!/usr/bin/env bash

# Runs all unit tests and performs static code analysis.
#
# Options:
#
#  --full   Include slower, more exhaustive tests and capture test coverage
#           results (outputs to .coverage.html).

# Exit on first failure.
set -e

# Echo commands before executing them, by default to stderr.
set -x

# Fail when piped commands fail.
set -o pipefail

full_test=""
# Without netgo and osusergo, compilation fails under Nix.
go_test_flags=("-tags=netgo,osusergo")
readonly COVERAGE_FILE_RAW=".coverage.out"
readonly COVERAGE_FILE_HTML=".coverage.html"
if [[ "$1" = "--full" ]]; then
  full_test="1"
  go_test_flags+=("-v")
  go_test_flags+=("-race")
  go_test_flags+=("--coverprofile=${COVERAGE_FILE_RAW}")
fi

# Exit on unset variable.
set -u

# Change directory to repository root.
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
readonly SCRIPT_DIR
cd "${SCRIPT_DIR}/.."

go test "${go_test_flags[@]}" ./...
if [[ -n "$full_test" ]]; then
  go tool cover -html "${COVERAGE_FILE_RAW}" -o "${COVERAGE_FILE_HTML}"
fi

go vet ./...

# Install staticcheck if it's not present.
STATICCHECK_PATH="$(go env GOPATH)/bin/staticcheck"
readonly STATICCHECK_PATH
readonly STATICCHECK_VERSION="v0.4.6"
if [[ ! -f "${STATICCHECK_PATH}" ]]; then
    go install \
      -ldflags=-linkmode=external \
      "honnef.co/go/tools/cmd/staticcheck@${STATICCHECK_VERSION}"
fi
"${STATICCHECK_PATH}" ./...

# Install errcheck if it's not present.
ERRCHECK_PATH="$(go env GOPATH)/bin/errcheck"
readonly ERRCHECK_PATH
readonly ERRCHECK_VERSION="v1.6.2"
if [[ ! -f "${ERRCHECK_PATH}" ]]; then
    go install \
      -ldflags=-linkmode=external \
      "github.com/kisielk/errcheck@${ERRCHECK_VERSION}"
fi
"${ERRCHECK_PATH}" -ignoretests ./...
